package com.baseweb.webadmin.controller.api;

import com.baseweb.webadmin.alipay.util.AlipayNotify;
import com.baseweb.webadmin.alipay.util.AlipayParams;
import com.baseweb.webadmin.controller.BaseController;
import com.baseweb.webadmin.core.constants.*;
import com.baseweb.webadmin.core.model.bvo.*;
import com.baseweb.webadmin.core.model.pojo.*;
import com.baseweb.webadmin.core.util.*;
import com.baseweb.webadmin.service.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping(value = "/api/product/")
public class ApiProductController extends BaseController {
    private Logger LOG = LoggerFactory.getLogger(ApiUserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private UserOrderService userOrderService;

    @Autowired
    private AccountService accountService;

    @ResponseBody
    @RequestMapping(value = "/channelList")
    public Map<String, Object> channelList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                       @RequestParam(value = "user_id", required = false) Integer user_id,
                                       @RequestParam(value = "product_type", required = false) Integer product_type,
                                       @RequestParam(value = "channel_id", required = false) Integer channel_id,
                                       @RequestParam(value = "parent_id", required = false) Integer parent_id,
                                       @RequestParam(value = "position_id", required = false) Integer position_id,
                                       @RequestParam(value = "sort", required = false) String sort,
                                       @RequestParam(value = "style_type", required = false) String style_type,
                                       @RequestParam(value = "price", required = false) String price,
                                       @RequestParam(value = "keyword", required = false) String keyword) {


        ChannelWithBizListBvo bizListBvo = null;
        List<User> bizList = userService.selectBizUserListByPage(product_type,null,channel_id,sort,style_type,price,keyword,(page-1)*pageSize, pageSize, null, null, null, null);
        if (parent_id.intValue() == 0 && position_id.intValue() == ChannelType.TOP_CHANNEL.getCode()){
            bizListBvo = ChannelWithBizListBvo.copyFrom(contentService.findChannel(channel_id), bizList);
        }else{
            List<ByChannel> channelList = contentService.selectChannelListByPage(position_id, channel_id, BaseState.NORMAL.getCode(), 0, Integer.MAX_VALUE);
            bizListBvo = ChannelWithBizListBvo.copyFrom(channelList, bizList);
        }

        return success(bizListBvo);
    }

    @ResponseBody
    @RequestMapping(value = "/getProductList")
    public Map<String, Object> getProductList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                               @RequestParam(value = "user_id", required = false) Integer user_id,
                               @RequestParam(value = "product_type", required = false) Integer product_type,
                               @RequestParam(value = "channel_id", required = false) Integer channel_id,
                               Model model) {
        if (pageSize == null || pageSize == 0) {
            pageSize = 20;
        }

        List<ByUserBizProduct> list = userService.selectProductListByPage(user_id, product_type, channel_id,(page-1)*pageSize, pageSize,
                null, null, null, null, BaseState.NORMAL.getCode());
        int total = userService.selectProductListCount(user_id, product_type, channel_id,
                null, null, null, null, BaseState.NORMAL.getCode());

        return success(list);
    }

    //商家列表
    @ResponseBody
    @RequestMapping(value = "/bizList")
    public Map<String, Object> bizList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                     @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                     @RequestParam(value = "user_id", required = false) Integer user_id,
                                     @RequestParam(value = "product_type", required = false) Integer product_type,
                                     @RequestParam(value = "channel_id", required = false) Integer channel_id,
                                     @RequestParam(value = "position_id", required = false) Integer position_id,
                                     @RequestParam(value = "sort", required = false) String sort,
                                     @RequestParam(value = "style_type", required = false) String style_type,
                                     @RequestParam(value = "price", required = false) String price,
                                     @RequestParam(value = "keyword", required = false) String keyword) {

        List<User> bizList = userService.selectBizUserListByPage(product_type,null,channel_id,sort,style_type,price,keyword,(page-1)*pageSize, pageSize, null, null, null,null);
        int total = userService.selectBizUserListCount(product_type,null,channel_id,sort,style_type,price,keyword, null, null, null);

        return success(bizList);
    }

    @ResponseBody
    @RequestMapping(value = "/biz_index", method = RequestMethod.GET)
    public Map<String, Object> biz_index(@RequestParam(value = "user_id", required = false) Integer user_id) {
        Map map = new HashMap();

        List<ByChannel> topList = contentService.selectChannelListByPage(ChannelType.TOP_CHANNEL.getCode(), 0, BaseState.NORMAL.getCode(), 0, 6);
        map.put("topList", topList);

        User user = userService.selectUserById(user_id);
        map.put("user", user);

        List<ByUserBizAuth> authList = userService.selectBizVerifyListByPage(user.getId(), null, null, 0,5, BaseState.NORMAL.getCode());
        map.put("authList", authList);

        List<ByUserBizProduct> productList = userService.selectProductListByPage(user.getId(), null, null, 0, 6,null,null,null,null);
        map.put("productList", productList);

        return success(map);
    }

    @ResponseBody
    @RequestMapping(value = "/indexRec", method = RequestMethod.GET)
    public Map<String, Object> indexRec(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {

        List<ByAd> curList = contentService.selectAdListByPage(AdPositionType.CURRENT_RECOMMEND.getCode(), 0,BaseState.NORMAL.getCode(), (page-1)*pageSize, pageSize);

        return success(curList);
    }


    //购物车
    @ResponseBody
    @RequestMapping(value = "/trolleyManage")
    public Map<String, Object> trolleyManage(@RequestParam(value = "token", defaultValue = "") String token,
                                            @RequestParam(value = "page", defaultValue = "1") Integer page,
                                            @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {

        if (!validatedRequest(token)){
            return illegalRequest();
        }

        User user = currentUser(token);

        List<ByUserTrolley> byUserTrolleys = userService.selectTrolleyListByPage(user.getId(), (page-1)*pageSize, pageSize);
        int total = userService.selectTrolleyListCount(user.getId());

        List<ByUserTrolleyBvo> list = new ArrayList<ByUserTrolleyBvo>();
        if (byUserTrolleys !=null && byUserTrolleys.size() > 0){
            for (ByUserTrolley current : byUserTrolleys){
                ByUserTrolleyBvo bvo = ByUserTrolleyBvo.copyFromByUserTrolley(current);
                bvo.setProduct(userService.findBizProduct(bvo.getProductId()));
                bvo.setUser(userService.selectUserById(bvo.getProduct().getUserId()));

                list.add(bvo);
            }
        }

        return success(list);
    }

    @ResponseBody
    @RequestMapping(value = "/addTrolley")
    public Map<String, Object> addTrolley(@RequestParam(value = "token", defaultValue = "") String token,
                                @RequestParam(value = "biz_user_id",required = false) Integer biz_user_id,
                                @RequestParam(value = "product_id",required = false) Integer product_id,
                                @RequestParam(value = "schedule_date",required = false) String schedule_date,
                                @RequestParam(value = "dinner_type",required = false) String dinner_type,
                              @RequestParam(value = "descn",required = false) String descn,
                              @RequestParam(value = "amount",defaultValue = "1") Integer amount) {
        if (!validatedRequest(token)){
            return illegalRequest();
        }

        User user = currentUser(token);

        if (product_id != null && product_id > 0) {
            ByUserTrolley byUserTrolley = new ByUserTrolley();
            byUserTrolley.setProductId(product_id);
            byUserTrolley.setUserId(user.getId());
            if (product_id != null && product_id.intValue() > 0){
                if (biz_user_id != null && biz_user_id.intValue() > 0){
                    byUserTrolley.setBizUserId(biz_user_id);
                }else{
                    byUserTrolley.setBizUserId(userService.findBizProduct(product_id).getUserId());
                }
            }

            if(amount == null || amount < 1){
                amount = 1;
            }

            byUserTrolley.setAmount(amount);

            byUserTrolley.setDescn(descn);
            byUserTrolley.setScheduleDate(DateUtil.getDateTime(schedule_date));
            byUserTrolley.setDinnerType(dinner_type);
            byUserTrolley.setCreateTime(new DateTime());
            byUserTrolley.setUpdateTime(new DateTime());

            userService.insertTrolley(byUserTrolley);

        }
        return success("");
    }

    @ResponseBody
    @RequestMapping(value = "/addDirectBuy")
    public Map<String, Object> addDirectBuy(@RequestParam(value = "token", defaultValue = "") String token,
                                @RequestParam(value = "product_id",required = false) Integer product_id,
                               @RequestParam(value = "biz_user_id",required = false) Integer biz_user_id,
                               @RequestParam(value = "schedule_date",required = false) String schedule_date,
                               @RequestParam(value = "dinner_type",required = false) String dinner_type,
                               @RequestParam(value = "amount",defaultValue = "1") Integer amount,
                               @RequestParam(value = "descn",required = false) String descn,
                               @RequestParam(value = "pay_status",required = false) Integer pay_status,
                               Model model) {

        if (!validatedRequest(token)){
            return illegalRequest();
        }

        User user = currentUser(token);

//        if (biz_user_id == null || biz_user_id < 1 || (biz_user_id.intValue() == user.getId().intValue())){
//            return "";
//        }

        ByUserOrder order = new ByUserOrder();
        if (product_id != null && product_id > 0) {
            ByUserBizProduct byUserBizProduct = userService.findBizProduct(product_id);
            User currentBizUser = userService.selectUserById(biz_user_id);

            order.setUserId(user.getId());

            order.setPayType(PayType.ALIPAY.getCode());
            order.setPayStatus(OrderPayStatus.NOT_PAY.getCode());
            order.setBizUserId(biz_user_id);
            order.setDescn(descn);
            order.setCreateTime(new DateTime());
            order.setUpdateTime(new DateTime());

            BigDecimal orderPrice = BigDecimal.ZERO;


            //更新订单价格
            if(amount == null || amount < 1){
                amount = 1;
            }

            order.setPrice(byUserBizProduct.getCurrentPrice().multiply(new BigDecimal(amount)));
            if (currentBizUser.getBizWorkType().intValue() == 1){ //策划师
                order.setStatus(OrderStatus.NEW_ORDER.getCode());
            }else{
                order.setStatus(OrderStatus.VERIFY_ORDER.getCode());
            }
            order.setDeposit(Constants.PRODUCT_DEPOSIT_RATIO.multiply(order.getPrice()));
            order.setNeedPayPrice(order.getPrice().subtract(order.getDeposit()));

            userOrderService.insertByUserOrder(order);


            //insert order detail

            ByUserOrderDetail detail = new ByUserOrderDetail();
            detail.setOrderId(order.getId());
            detail.setUserId(user.getId());
            detail.setProductId(product_id);

            detail.setAmount(amount);
            detail.setPrice(order.getPrice());

            detail.setScheduleDate(DateUtil.getDateTime(schedule_date));
            detail.setDinnerType(dinner_type);
            detail.setBizUserId(byUserBizProduct.getUserId());
            detail.setOrderId(order.getId());
            detail.setDeposit(Constants.PRODUCT_DEPOSIT_RATIO.multiply(detail.getPrice()));
            detail.setCreateTime(new DateTime());
            detail.setUpdateTime(new DateTime());
            userOrderService.insertByUserOrderDetail(detail);

            //add Schedule
            ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
            byUserBizSchedule.setUserId(biz_user_id);
            byUserBizSchedule.setScheduleDate(detail.getScheduleDate());
            byUserBizSchedule.setStatus(BaseState.NORMAL.getCode());
            byUserBizSchedule.setScheduleType(ScheduleType.getByName(detail.getDinnerType()).getCode());
            byUserBizSchedule.setOrderBy(detail.getUserId());
            byUserBizSchedule.setCreateTime(new DateTime());
            byUserBizSchedule.setUpdateTime(new DateTime());

            userOrderService.insertSchedule(byUserBizSchedule);

        }

        OrderWithDetailBvo bvo = OrderWithDetailBvo.copyFrom(OrderBvo.copyFrom(order,
                userService.selectUserById(order.getUserId()),
                userService.selectUserById(order.getBizUserId())), null);

        return success(bvo);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteTrolley")
    public Map<String, Object> deleteTrolley(@RequestParam(value = "token", defaultValue = "") String token,
                                    @RequestParam(value = "trolley_id",required = false) Integer trolley_id) {

        if (!validatedRequest(token)){
            return illegalRequest();
        }

        userService.deleteTrolley(trolley_id);

        return success("");
    }



    @ResponseBody
    @RequestMapping(value = "/getOrderList")
    public Map<String, Object> getOrderList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                             @RequestParam(value = "token",required = true) String token,
                             Model model) {
        if (!validatedRequest(token)){
            return illegalRequest();
        }

        User user = currentUser(token);
//        List<ByUserOrder> list = userOrderService.selectOrderListByPage(user.getId(), (page-1)*pageSize, pageSize);
//        int total = userOrderService.selectOrderListCount(user.getId());

        List<ByUserOrder> list = userOrderService.selectAllOrderListByPage(user.getId(), (page-1)*pageSize, pageSize);

        List<OrderBvo> orderBvos = new ArrayList<OrderBvo>();
        for(ByUserOrder current : list){
            OrderBvo bvo = OrderBvo.copyFrom(current, userService.selectUserById(current.getUserId()), userService.selectUserById(current.getBizUserId()));
            orderBvos.add(bvo);
        }

        return success(orderBvos);
    }

    @ResponseBody
    @RequestMapping(value = "/getOrderDetailList")
    public Map<String, Object> getOrderDetailList(@RequestParam(value = "token",required = true) String token,
                                   @RequestParam(value = "order_id",required = true) Integer order_id) {
        if (!validatedRequest(token)){
            return illegalRequest();
        }

        ByUserOrder byUserOrder = userOrderService.findByUserOrder(order_id);

        Map<String, Object> result = new HashMap<String, Object>();
        User user = currentUser(token);
        List<ByUserOrderDetail> list = userOrderService.selectOrderDetailListByPage(user.getId(), order_id,0, Integer.MAX_VALUE);
//        int total = userOrderService.selectOrderDetailListCount(user.getId(), order_id);

        List<ByUserOrderDetailInfoBvo> productList = new ArrayList<ByUserOrderDetailInfoBvo>();

        if (list != null && list.size() > 0){   //
            List<Integer> productIds = new ArrayList<Integer>();
            for(ByUserOrderDetail current : list){
                ByUserOrderDetailInfoBvo bvo = ByUserOrderDetailInfoBvo.copyFrom(current, userService.selectUserById(current.getUserId()), userService.selectUserById(current.getBizUserId()), userService.findBizProduct(current.getProductId()));
                productList.add(bvo);
            }

//            productList = userService.findBizProductList(productIds);
        }

        OrderWithDetailBvo bvo = OrderWithDetailBvo.copyFrom(OrderBvo.copyFrom(byUserOrder,
                userService.selectUserById(byUserOrder.getUserId()),
                userService.selectUserById(byUserOrder.getBizUserId())), productList);

        return success(bvo);
    }

    @ResponseBody
    @RequestMapping(value = "/submitOrder")
    public Map<String, Object> submitOrder(@RequestParam(value = "token",required = true) String token,
                                           @RequestParam(value = "descn",defaultValue = "") String descn) {
        try{
            if (!validatedRequest(token)){
                return illegalRequest();
            }

            User user = currentUser(token);

            List<ByUserTrolley> byUserTrolleys = userService.selectTrolleyListByPage(user.getId(), 0, Integer.MAX_VALUE);

            Map<Integer, List<ByUserTrolley>> tmpMap = new HashMap<Integer, List<ByUserTrolley>>();
            if (byUserTrolleys !=null && byUserTrolleys.size() > 0){
                Set set = new HashSet();

                for (ByUserTrolley current : byUserTrolleys){
                    if(set.contains(current.getBizUserId())){
                        tmpMap.get(current.getBizUserId()).add(current);
                    }else{
                        List<ByUserTrolley> tmpList = new ArrayList<ByUserTrolley>();
                        tmpList.add(current);
                        tmpMap.put(current.getBizUserId(), tmpList);

                        set.add(current.getBizUserId());
                    }
                }

                for(Iterator it = tmpMap.keySet().iterator(); it.hasNext();) {
                    Integer mKey = (Integer) it.next();
                    User currentBizUser = userService.selectUserById(mKey);

                    ByUserOrder order = new ByUserOrder();
                    order.setUserId(user.getId());
                    order.setDescn(descn);

                    order.setPayType(PayType.ALIPAY.getCode());
                    order.setPayStatus(OrderPayStatus.NOT_PAY.getCode());
                    order.setBizUserId(mKey);
                    order.setCreateTime(new DateTime());
                    order.setUpdateTime(new DateTime());

                    userOrderService.insertByUserOrder(order);

                    BigDecimal orderPrice = BigDecimal.ZERO;
                    for (ByUserTrolley current : tmpMap.get(mKey)){
                        ByUserBizProduct byUserBizProduct = userService.findBizProduct(current.getProductId());

                        ByUserOrderDetail detail = new ByUserOrderDetail();
                        detail.setOrderId(order.getId());
                        detail.setUserId(user.getId());

                        if(current.getAmount() == null || current.getAmount() < 1){
                            detail.setAmount(1);
                        }else{
                            detail.setAmount(current.getAmount());
                        }

                        detail.setProductId(current.getProductId());
                        detail.setPrice(byUserBizProduct.getCurrentPrice().multiply(new BigDecimal(current.getAmount())));

                        orderPrice = orderPrice.add(detail.getPrice());

                        detail.setScheduleDate(current.getScheduleDate());
                        detail.setDinnerType(current.getDinnerType());
                        detail.setBizUserId(byUserBizProduct.getUserId());
                        detail.setOrderId(order.getId());
                        detail.setDeposit(Constants.PRODUCT_DEPOSIT_RATIO.multiply(detail.getPrice()));
                        detail.setCreateTime(new DateTime());
                        detail.setUpdateTime(new DateTime());
                        userOrderService.insertByUserOrderDetail(detail);

                        //add Schedule
                        ByUserBizSchedule byUserBizSchedule = new ByUserBizSchedule();
                        byUserBizSchedule.setUserId(current.getBizUserId());
                        byUserBizSchedule.setOrderBy(detail.getUserId());
                        byUserBizSchedule.setScheduleDate(detail.getScheduleDate());
                        byUserBizSchedule.setStatus(BaseState.NORMAL.getCode());
                        byUserBizSchedule.setScheduleType(ScheduleType.getByName(detail.getDinnerType()).getCode());
                        byUserBizSchedule.setCreateTime(new DateTime());
                        byUserBizSchedule.setUpdateTime(new DateTime());

                        userOrderService.insertSchedule(byUserBizSchedule);
                    }

                    ByUserOrder newOrder = userOrderService.findByUserOrder(order.getId());

                    //更新订单价格
                    newOrder.setPrice(orderPrice);
                    if (currentBizUser.getBizWorkType().intValue() == 1){ //策划师
                        newOrder.setStatus(OrderStatus.NEW_ORDER.getCode());
                    }else{
                        newOrder.setStatus(OrderStatus.VERIFY_ORDER.getCode());

                        //send msg
//                        Map<String, Object> map = new LinkedHashMap<String, Object>();
//                        map.put("code", ""+newOrder.getStatus());
//
//                        CommonUtil.sendMessage(currentBizUser.getMobile(), JSONObject
//                                .fromObject(map).toString(), ConfigUtil
//                                .getSms_template_code_new_order());
                    }
                    newOrder.setDeposit(Constants.PRODUCT_DEPOSIT_RATIO.multiply(newOrder.getPrice()));
                    newOrder.setNeedPayPrice(newOrder.getPrice().subtract(newOrder.getDeposit()));

                    userOrderService.insertByUserOrder(newOrder);
                }
            }

            userService.deleteTrolleyByUserAndProduct(user.getId(), null);

            return  success("提交成功");
        }catch (Exception ex){
            ex.printStackTrace();
            return  fail("提交失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/submitOrderComment")
    public Map<String, Object> submitOrderComment(@RequestParam(value = "order_id",required = false) Integer order_id,
                                     @RequestParam(value = "user_stars",defaultValue = "5") Integer user_stars,
                                     @RequestParam(value = "descn",required = false) String descn,
                                     Model model) {
        if (order_id !=null && order_id > 0) {
            ByUserOrder byUserOrder = userOrderService.findByUserOrder(order_id);
            byUserOrder.setUserStars(user_stars);
            byUserOrder.setUserComment(descn);

            userOrderService.insertByUserOrder(byUserOrder);
        }

        return success("");
    }

    @ResponseBody
    @RequestMapping(value = "/submitSchedule")
    public Map<String, Object> submitSchedule(@RequestParam(value = "token",required = false) String token,
                                @RequestParam(value = "id",required = false) Integer id,
                                 @RequestParam(value = "schedule_date",required = false) String schedule_date,
                                 @RequestParam(value = "schedule_type",defaultValue = "0") Integer schedule_type,
                                 @RequestParam(value = "status",required = false) Integer status) {
        try{
            if (!validatedRequest(token)){
                return illegalRequest();
            }

            User user = currentUser(token);

            if (user.getUserType().intValue() == UserType.NORMAL_BIZ.getCode() || user.getUserType().intValue() == UserType.TEAM_BIZ.getCode()){
                //            boolean isScheduled = userOrderService.isScheduled(user.getId(), BaseState.NORMAL.getCode(), DateUtil.getDateTime(schedule_date), schedule_type);
//            if (isScheduled){
//                return fail("档期已被预订,不能添加!");
//            }

                ByUserBizSchedule byUserBizSchedule = null;
                if (status == 1){
                    if (id != null && id > 0) {
                        userOrderService.deleteSchedule(id);
                    }
                }else if(status == -1){
                    byUserBizSchedule = new ByUserBizSchedule();
                    byUserBizSchedule.setUserId(user.getId());
                    byUserBizSchedule.setScheduleDate(DateUtil.getDateTime(schedule_date));
                    byUserBizSchedule.setStatus(status);
                    byUserBizSchedule.setScheduleType(schedule_type);
                    byUserBizSchedule.setCreateTime(new DateTime());
                    byUserBizSchedule.setUpdateTime(new DateTime());

                    userOrderService.insertSchedule(byUserBizSchedule);
                }
                return success("操作成功!");
            }else{
                return fail("非商家不能新增档期!");
            }
        }catch (Exception ex){
            return fail("操作失败!");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getScheduleList")
    public Map<String, Object> getScheduleList(@RequestParam(value = "token",required = false) String token,
                                @RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {
        if (!validatedRequest(token)){
            return illegalRequest();
        }

        User user = currentUser(token);

        List<ByUserBizSchedule> list = userOrderService.selectScheduleListByPage(user.getId(), null, (page-1)*pageSize, pageSize);
        int total = userOrderService.selectScheduleListCount(user.getId(), null);

        return success(list);
    }

    @ResponseBody
    @RequestMapping(value = "/sendRedPacket")
    public Map<String, Object> sendRedPacket(@RequestParam(value = "token",required = false) String token,
                                            @RequestParam(value = "id",required = false) Integer id,
                                            @RequestParam(value = "red_packet_type",required = false) Integer red_packet_type,
                                            @RequestParam(value = "red_packet_money",required = false) String red_packet_money,
                                Model model) {
        try{
            if (!validatedRequest(token)){
                return illegalRequest();
            }

            User user = currentUser(token);

            ByUserOrder byUserOrder = null;
            if (id != null && id > 0){
                byUserOrder = userOrderService.findByUserOrder(id);
            }else{
                byUserOrder = new ByUserOrder();
            }
            byUserOrder.setRedPacketMoney(ObjectFormatter.str2BigDecimal(red_packet_money));
            byUserOrder.setUpdateTime(new DateTime());

            userOrderService.insertByUserOrder(byUserOrder);

            if (red_packet_type != null && red_packet_type.intValue() != 1 && Float.parseFloat(red_packet_money) > 0) {
                ByMoneyLog byMoneyLog = new ByMoneyLog();
                byMoneyLog.setUserId(user.getId());
                byMoneyLog.setAmount(ObjectFormatter.str2BigDecimal(red_packet_money));
                byMoneyLog.setMoneyType(MoneyType.RED_PACKET.getCode());
                byMoneyLog.setCreateTime(new DateTime());
                byMoneyLog.setUpdateTime(new DateTime());
                accountService.insertMoneyLog(byMoneyLog);

                user.setMoney(user.getMoney().add(ObjectFormatter.str2BigDecimal(red_packet_money)));
                userService.updateUser(user);
            }

            return success("");
        }catch (Exception ex){
            return fail("");
        }
    }

    @ResponseBody
    @RequestMapping(value = "/orderCancel")
    public Map<String, Object> orderCancel(@RequestParam(value = "token",required = false) String token,
                            @RequestParam(value = "order_id", required = true) Integer order_id,
                            Model model) {
        if (!validatedRequest(token)){
            return illegalRequest();
        }

        User user = currentUser(token);

//        List<ByUserVoucher> list = accountService.selectVoucherListByPage(user.getId(), (page-1)*pageSize, pageSize);
//        int total = accountService.selectVoucherListCount(user.getId());
//        model.addAttribute("list", list);
//        model.addAttribute("total", total);
//        model.addAttribute("pageSize", pageSize);

        return success("");
    }

    //for user use
    @ResponseBody
    @RequestMapping(value = "/orderChangeStatus")
    public Map<String, Object> orderChangeStatus(@RequestParam(value = "token",required = false) String token,
                                    @RequestParam(value = "order_id", required = true) Integer order_id,
                                    @RequestParam(value = "status", required = true) Integer status,
                                    Model model) {
        if (!validatedRequest(token)){
            return illegalRequest();
        }

        if (order_id != null && status != null){
            User user = currentUser(token);

            ByUserOrder order = userOrderService.findByUserOrder(order_id);

            if (user.getId().intValue() == order.getUserId().intValue()) {

                order.setStatus(status);
                order.setUpdateTime(new DateTime());

                userOrderService.insertByUserOrder(order);

                if (status == OrderStatus.CONFIRM_ORDER.getCode()){
                    User bizUser = userService.selectUserById(order.getBizUserId());

                    if (bizUser.getBizDealCount() != null && bizUser.getBizDealCount() > 0) {
                        bizUser.setBizDealCount(bizUser.getBizDealCount() + 1);
                    }else{
                        bizUser.setBizDealCount(1);
                    }
                    userService.updateUser(bizUser);
                }
            }else{
                return fail("非法操作!");
            }
        }

        return success("操作成功");
    }

    //for biz use
    @ResponseBody
    @RequestMapping(value = "/orderBizChangeStatus")
    public Map<String, Object> orderBizChangeStatus(@RequestParam(value = "token",required = false) String token,
                                       @RequestParam(value = "order_id", required = true) Integer order_id,
                                       @RequestParam(value = "status", required = true) Integer status,
                                       Model model) {

        if (!validatedRequest(token)){
            return illegalRequest();
        }

        if (order_id != null && status != null){
            User user = currentUser(token);

            ByUserOrder order = userOrderService.findByUserOrder(order_id);

            if (user.getId().intValue() == order.getBizUserId().intValue()) {
                order.setStatus(status);
                order.setUpdateTime(new DateTime());

                userOrderService.insertByUserOrder(order);

                if (status.intValue() == OrderStatus.BIZ_RECEIVE_ORDER.getCode()){
                    User orderUser = userService.selectUserById(order.getUserId());

                    //send msg
                    Map<String, Object> map = new LinkedHashMap<String, Object>();
                    map.put("code", ""+order.getId());

                    CommonUtil.sendMessage(orderUser.getMobile(), JSONObject
                            .fromObject(map).toString(), ConfigUtil
                            .getSms_template_code_order_receive());
                }

            }else{
                return fail("非法操作!");
            }
        }

        return success("操作成功");
    }


    @ResponseBody
    @RequestMapping(value = "/getBizOrderList")
    public Map<String, Object> getBizOrderList(@RequestParam(value = "token",required = false) String token,
                                @RequestParam(value = "page", defaultValue = "1") Integer page,
                                @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize,
                                @RequestParam(value = "user_id",required = false) Integer user_id,
                                Model model) {
        if (!validatedRequest(token)){
            return illegalRequest();
        }

//        User user = getCurrentUser();
        List<ByUserOrder> list = userOrderService.selectBizOrderListByPage(user_id, OrderStatus.VERIFY_ORDER.getCode(), (page-1)*pageSize, pageSize);
        int total = userOrderService.selectBizOrderListCount(user_id, OrderStatus.VERIFY_ORDER.getCode());
        model.addAttribute("list", list);
        model.addAttribute("total", total);
        model.addAttribute("pageSize", pageSize);

        return success(list);
    }

    @ResponseBody
    @RequestMapping(value = "/getIndexRecList")
    public Map<String, Object> getBizOrderList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                               @RequestParam(value = "pageSize", defaultValue = "20") Integer pageSize) {

        List<ByAd> curList = contentService.selectAdListByPage(AdPositionType.CURRENT_RECOMMEND.getCode(), 0, BaseState.NORMAL.getCode(), (page-1)*pageSize, pageSize);

        List<ByAd> lunboList = contentService.selectAdListByPage(AdPositionType.INDEX_LUNBO.getCode(), 0, BaseState.NORMAL.getCode(), 0, 5);

        return success(curList, lunboList);
    }














    @RequestMapping(value="/ordersPay")
    public void ordersPay(HttpServletRequest request, HttpServletResponse response) throws IOException{

        LOG.debug("支付宝支付服务器异步通知请求    orderNum="+request.getParameter("out_trade_no"));
        PrintWriter out = response.getWriter();
        String orderNum = request.getParameter("out_trade_no");

        //获取支付宝POST过来反馈信息
        Map<String,String>  params= AlipayParams.getAlipayParamsForMap(request);

        ByUserOrder oldOrder = userOrderService.findByUserOrder(Integer.valueOf(orderNum));

        ByUserOrder  orders =AlipayParams.getAlipayParamsForOrder(oldOrder, params);
        String trade_status=orders.getAlipaytradestatus();

        if((params.size()>=1 && AlipayNotify.verify(params) && params.get("notify_type")!=null && params.get("notify_type").trim().equals("trade_status_sync") )){
            /**
             * a、在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS或TRADE_FINISHED  时，支付宝才会认定为买家付款成功
             * b、交易状态 TRADE_SUCCESS 的通知触发条件是商户签约的产品支持退款功能的前提下，买家付款成功；
             * c、交易状态 TRADE_FINISHED 的通知触发条件是商户签约的产品不支持退款功能的前提下，买家付款成功；或者，商户签约的产品支持退款功能的前提下，交易已经成功并且已经超过可退款期限；
             */
            if( trade_status!=null && (trade_status.trim().equals("TRADE_FINISHED") || trade_status.trim().equals("TRADE_SUCCESS"))){
                LOG.debug("支付宝(支付完成;买家付款成功)异步通知: success");
                orders.setPayType(Const.OrdersPayMethod.ALIPAY);



                orders.setNeedPayPrice(oldOrder.getPrice().subtract(orders.getAlipaytotalfee()));

                if (orders.getNeedPayPrice().equals(BigDecimal.ZERO)){
                    orders.setPayStatus(OrderPayStatus.PAY_ALL.getCode());
                }else {
                    orders.setPayStatus(OrderPayStatus.PAY_DEPOSIT.getCode());
                }

                userOrderService.insertByUserOrder(orders);

//				out.println("success".toString().trim());	//请不要修改或删除
                out.print("success".toString().trim());	//请不要修改或删除
            }else{
                LOG.debug("支付(卖买家付款还未完成)宝异步通知: trade_status="+trade_status);
                out.print("fail".toString().trim());
            }
        }else{
            LOG.debug("支付宝异步通知校验不合法: fail--数字校验未通过");
            out.print("fail".toString().trim());
        }
    }

    /**
     * 商家子订单退款异步通知接口
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/orderBusinessRefund")
    public void orderBusinessRefund(HttpServletRequest request, HttpServletResponse response) throws IOException{

        LOG.debug("doRequest(interface/orderBusinessRefund)--支付宝支付服务器(退款)异步通知请求");
        PrintWriter out = response.getWriter();

        //获取支付宝POST过来反馈信息
//        Map<String,String>  params=AlipayParams.getAlipayParamsForMap(request);
//        OrdersBusiness  ordersBusiness =AlipayParams.getAlipayParamsForOrdersBusiness(params);
//        String trade_status=params.get("trade_status");
//
//
//        if((params.size()>=1 && AlipayNotify.verify(params))){
//            if(params.get("notify_type")!=null && params.get("notify_type").trim().equals("trade_status_sync")){
//                if(trade_status!=null && (trade_status.trim().equals("TRADE_CLOSED"))){
//                    //交易关闭处理，即用户已完成了全部退款
//                    LOG.debug("支付宝(交易关闭处理，即用户已完成了全部退款)异步通知: success");
//                }else{
//                    LOG.debug("支付宝(交易未关闭，执行了部分退款操作)异步通知: success");
//                }
//                out.print("success");	//请不要修改或删除
//                return;
//            }else if(params.get("notify_type")!=null && params.get("notify_type").trim().equals("batch_refund_notify")){
//                String  result_details=params.get("result_details");
//                if(result_details==null){
//                    LOG.debug("支付宝退款返回的退款详细信息错误： result_details=" +result_details);
//                    out.print("fail");
//                    return;
//                }
//                String[] result_detailsArray=result_details.split("^");
//                if(result_detailsArray.length<=3 || !result_detailsArray[2].trim().equals("SUCCESS")){
//                    LOG.debug("支付宝退款返回的退款详细信息错误： result_details=" +result_details);
//                    out.print("fail");
//                    return;
//                }
//
//                if(result_detailsArray[2].trim().equals("SUCCESS")){
//
//                    //退款成功后业务操作
////                    ordersService.doOrdersBusinessRefund(ordersBusiness);
//                    LOG.debug("支付宝(该笔退款成功)退款异步通知： success");
//                    out.print("success");	//请不要修改或删除
//                    return;
//                }
//
//
//            }else{
//                LOG.debug("支付宝(退款)异步通知校验不合法: fail---notify_type="+params.get("notify_type"));
//                out.print("fail");
//                return;
//            }
//
//        }else{
//            LOG.debug("支付宝(退款)异步通知校验不合法: fail---数字验签未通过");
//            out.print("fail");
//            return;
//        }


    }
}
